package codeTop;

public class BinarySearch {
    //找target位置，没有返回-1
    public int binary(int[] nums,int target){
        int l = 0;
        int r = nums.length-1;
        while (l <= r) {
            int mid = l+(r-l)/2;
            if (nums[mid] == target) {
                return mid;
            }else if (nums[mid]<target){
                l = mid + 1;
            }else {
                r = mid - 1;
            }
        }
        return -1;
    }

    //找第一个大于等于target的位置，用于插入
    public int binaryInsert(int[] nums,int target){
        int l = 0;
        int r = nums.length;
        while (l < r) {
            int mid = l+(r-l)/2;
            if (nums[mid] < target) {
                l = mid+1;
            }else{
                r = mid;
            }
        }
        return l;
    }

}
